from PIL import Image, ImageDraw
import imageio
import os


def draw(girl_img):
    pix = [".", ",", "'", ";", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")"]
    new_im = girl_img.convert("L")

    newL = Image.new("L", (new_im.width, new_im.height), 255)  # 将彩色图转为黑白图
    # newL.show()
    draw = ImageDraw.Draw(newL)  # 创建可画字符的图对象
    fillColor = "#ff0000"
    for x in range(0, new_im.width, 6):  # 双层循环对原图片每一个像素进行分析  这里每隔6个像素取一个像素，
        for y in range(0, new_im.height, 6):  # 因为像素相对字符小很多，如果每个像素都取的话，那么图就变成密密麻麻的字符了
            # newL.putpixel((x, y), new_im.getpixel((x, y)))
            xy_degree = new_im.getpixel((x, y))
            index = int(xy_degree/(256/len(pix)))
            draw.text((x, y), pix[index], fill=fillColor)  # 根据像素值取相应字符画到对应的坐标点上
    return newL


def img_src():
    gif_img = Image.open("active_demo.gif")
    lx = gif_img.tell()
    gif_img.seek(lx)
    i = 0
    try:
        while True:
            img_i = draw(gif_img)
            img_i.save("imgs/img"+str(i)+".png")
            gif_img.seek(gif_img.tell() + 1)
            i += 1
    except EOFError:
        pass


def create_gif():
    files = os.listdir("imgs")
    frames = []
    for i in range(len(files)):
        frames.append(imageio.imread("imgs/img"+str(i)+".png"))

    imageio.mimsave("lovely.gif", frames, 'GIF', duration = 0.1)


if __name__ == '__main__':
    # img_src()
    create_gif()